import 'package:after_sale_plugin/pages/order_detail/state.dart';

import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:wechat_assets_picker_plus/wechat_assets_picker_plus.dart';
import '../../constant.dart';
import '../../package_data_center.dart';
import '../../package_event.dart';
import '../models/order_model.dart';
import 'cell/problem_content_view.dart';

class OrderDetailController extends LxBaseScrollOpacityController {
  // 工单详情
  OrderDetailState state = OrderDetailState();

  @override
  onInit() async {
    super.onInit();

    // 页面数据
    if (Get.arguments != null) {
      getOrderDetail(Get.arguments);
    } else {
      if (PackageDataCenter.orderId.isNotEmpty) {
        getOrderDetail(PackageDataCenter.orderId);
      }
    }

    // 监听 资源文件
    state.supplementAssets.listen((p0) {
      state.supplementAssetsUploadCompleted.value =
          p0.every((element) => element.src.isNotEmpty || element.isAdd);
      state.allowedSubmit.value =
          p0.where((element) => !element.isAdd).toList().isNotEmpty ||
              state.supplementContent.value.isNotEmpty;
    });

    // 监听 文本内容
    state.supplementContent.listen((p0) {
      state.allowedSubmit.value = state.supplementAssets
              .where((element) => !element.isAdd)
              .toList()
              .isNotEmpty ||
          p0.isNotEmpty;
    });
  }

  // 获取订单详情
  getOrderDetail(String id) {
    state.id = id;
    PackageEvent.orderDetail(
      (p0) {
        ReportOrderInfo reportOrderInfo =
            ReportOrderInfo.fromMap(p0 as Map<String, dynamic>);
        reportOrderInfo.id = id;
        // 工单信息
        state.reportOrderInfo.value = reportOrderInfo;
        state.orderProgressState.value =
            reportOrderInfo.orderProgressState.value;
        state.problemDescContent.value = reportOrderInfo.problemContent.value;
        state.repairAssets.value = reportOrderInfo.assetModels;
        state.orderInfos.first.val.value = reportOrderInfo.id;
        state.orderInfos.last.val.value = reportOrderInfo.submitedDate;
        state.repairDetails.first.val.value =
            reportOrderInfo.reportVehicleName.value;
        state.repairDetails[1].val.value = reportOrderInfo.sn;
        state.repairDetails.last.val.value =
            reportOrderInfo.reportTypeDesc.value;
        state.orderHistorys.first.val.value = reportOrderInfo.submitedDate;
        if (reportOrderInfo.startedTimeStamp.value != 0) {
          state.orderHistorys[1].val.value = reportOrderInfo.startedDate;
        }
        if (reportOrderInfo.completeTimeStamp.value != 0) {
          state.orderHistorys[2].val.value = reportOrderInfo.completeDate;
        }
        if (reportOrderInfo.closedTimeStamp.value != 0) {
          state.orderHistorys.last.val.value = reportOrderInfo.closedDate;
        }
        // 是否显示feedback
        state.showFeedbackAssets.value = reportOrderInfo.feedback.isNotEmpty;
        state.needToSupplementAssets.value = reportOrderInfo.needFeedback.value;
        if (reportOrderInfo.feedback.isNotEmpty) {
          state.supplementAssets.value = reportOrderInfo
              .feedback.first.attachment
              .map((element) => AssetModel.fromMap({})..src = element)
              .toList();
          state.feedbackContent.value =
              reportOrderInfo.feedback.first.comment.value;
        }
        // 问题解决状态
        switch (reportOrderInfo.resolutionResult.value.state.value) {
          case ResolutionStatus.none:
            state.problemResolvedState.value = ProblemResolvedState.unselected;
            break;
          case ResolutionStatus.resolved:
            state.problemResolvedState.value = ProblemResolvedState.resolved;
            break;
          case ResolutionStatus.unsolved:
            state.problemResolvedState.value = ProblemResolvedState.unsolved;
            break;
        }
        state.problemResolutionContent.value =
            reportOrderInfo.resolutionResult.value.resolution.value;
      },
      param: state.id,
    );
  }

  // 重新提交 资源文件
  submitAgain() {
    bool isSubmited = false;
    submit() {
      if (isSubmited) return;
      ReportOrderInfo reportOrderInfo = ReportOrderInfo.fromMap({});
      reportOrderInfo.id = state.id;
      reportOrderInfo.supplementContent = state.supplementContent.value;
      reportOrderInfo.feedback.add(FeedbackModel.fromMap({})
        ..attachment.value =
            state.supplementAssets.map((element) => element.src).toList());
      PackageEvent.updateOrder((p0) {
        if (p0) {
          PackageEvent.showConfirmAlert(
            AppLanguageUtil.to.submitOrderSuccessPrompts,
            confirmTitle: AppLanguageUtil.to.titleOK,
            isShowCancel: false,
            confirmCallBack: (p0) {
              // 重新获取订单详情
              getOrderDetail(state.id);
            },
          );
        }
      }, param: reportOrderInfo.toJson());
      isSubmited = true;
    }

    if (state.supplementAssetsUploadCompleted.value) {
      submit();
    } else {
      PackageEvent.showLoading();
      state.supplementAssetsUploadCompleted.listen((p0) {
        if (p0) submit();
      });
      // 5秒后，无论是否上传完成，都进行提交
      Future.delayed(const Duration(seconds: 5), () {
        submit();
      });
    }
  }

  // 已解决
  orderResolved() {
    PackageEvent.orderResolved((p0) {
      if (p0) {
        state.orderProgressState.value = OrderProgressState.closed;
        Future.delayed(const Duration(milliseconds: 500), () {
          PackageEvent.showToast(AppLanguageUtil.to.orderCommentedPrompts);
        });
        PackageEventStream().fire(REFRESH_ORDER_LIST);
      }
    }, param: state.id);
  }
}
